package com.wanmait.movie.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.movie.constant.UserContsant;
import com.wanmait.movie.entity.Admin;
import com.wanmait.movie.entity.User;
import com.wanmait.movie.service.AdminService;
import com.wanmait.movie.service.UserService;
import com.wanmait.movie.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查是否预检请求，如果是预检请求放行
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        //从请求头中获得token
        String token = request.getHeader("token");
        System.out.println(token);
        if(token==null){
            throw new JWTVerificationException("没有携带token令牌");
        }
        //获得签发对象，用的是用户的id
        Integer id = null;
        String roles = null;

        try {
            id = Integer.parseInt(JWTUtils.getAudience(token));
            roles = JWTUtils.getClaimByName(token,"roles");
        } catch (NumberFormatException e) {
            throw new JWTVerificationException("解析token获得签发对象失败");
        }
        //获得admin
        Admin admin = adminService.getById(id);
        User user = userService.getById(id);
        if(admin==null||user==null){
            throw new JWTVerificationException("没有查询到用户信息");
        }
        if (roles.equals("user")){
            JWTUtils.verifyToken(token, UserContsant.SECRET_KEY);
            //共享admin，在控制器的功能处理方法中或者切面类中都可以使用
            request.setAttribute("user", user);
        } else if (roles.equals("admin")){
            //验证token
            JWTUtils.verifyToken(token, admin.getPassword());
            //共享admin，在控制器的功能处理方法中或者切面类中都可以使用
            request.setAttribute("admin", admin);
        }
        return true;
    }
}
